var os = require('os');
var fs = require('fs');
var del = require('del');
var through = require('through2');
var gulp = require('gulp');
var gutil = require('gulp-util');
var brfs = require('brfs');
var browserify = require('browserify');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var sourcemaps = require('gulp-sourcemaps');
// var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var Browsersync = require("browser-sync").create();
var tpl = require('tpl-index');
var log = gutil.log;

var config = JSON.parse(fs.readFileSync('./package.json', 'utf-8')).config || {};

gulp.task('log', function(){
	log(config)
})


gulp.task('clean', function(){
	del.sync(['dist']);
});

gulp.task('copy', function(){
	return gulp.src('./src/assets/xscript/**/*').pipe(gulp.dest('./dist/mstatic/xscript'));
});


// <!-- wptr -->
var wptrjs = function(){
	var stream = through.obj(function(file, enc, cb) {
		if (file.isStream()) {
			return cb();
		}

		if (file.isBuffer()) {
			var prefix = new Buffer("var $ = require('jquery');\r\nvar Hammer = require('hammer');\r\n");
			var suffix = new Buffer("\r\nmodule.exports = WebPullToRefresh;");
			var content = new Buffer(file.contents.toString("utf-8").replace(/\/\/@import[^\r\n]+/g, ''));

			file.contents = Buffer.concat([prefix, content, suffix]);
		}

		this.push(file);


		cb();
	});


	return stream;
};

var wptrcss = function(isComment){
	var stream = through.obj(function(file, enc, cb) {
		if (file.isStream()) {
			return cb();
		}

		if (file.isBuffer()) {
			var reg = /\/*(@import\s+\"_wptr\";)/;
			file.contents = new Buffer(file.contents.toString("utf-8").replace(reg, isComment ? '//$1' : '$1'));
		}

		this.push(file);


		cb();
	});


	return stream;
};

gulp.task('wptr-js', function(){
	var dir = '../../common/js/assets/pullRefresh';
	var js = '/wptr.1.1.plus.js';
	var js2 = './src/node_modules/wptr';
	var jsname = 'wptr.js';

	return gulp.src(dir + js)
		.pipe(wptrjs())
		.pipe(rename(jsname))
		.pipe(gulp.dest(js2));
	
});

gulp.task('wptr-css', function(){
	var dir = '../../common/js/assets/pullRefresh';
	
	var css = '/base.plus.css';
	var css2 = './src/css';
	var cssname = '_wptr.css';

	return gulp.src(dir + css)
		.pipe(rename(cssname))
		.pipe(gulp.dest(css2));
});
/*
gulp.task('wptr-icon', function(){
	var dir = '../../common/js/assets/pullRefresh';
	var icon = '/genericons/**';
	var icon2 = './src/css/genericons';
	

	return gulp.src(dir + icon)
		.pipe(gulp.dest(icon2));
});*/

gulp.task('wptr-clean', function(){
	del.sync(['./src/css/genericons', './src/css/_wptr.css', './src/node_modules/wptr/wptr.js']);
});

gulp.task('wptr', ['wptr-js', 'wptr-css']);



// <!-- scss -->
// sass type: nested, expanded, compact, compressed
gulp.task('scss', function(){
	return gulp.src('./src/css/webim.scss')
		.pipe(wptrcss(false))
		.pipe(sourcemaps.init({loadMaps: true}))
		.pipe(sass.sync({outputStyle: config.sass.type}).on('error', sass.logError))
		.pipe(sourcemaps.write('./'))
		.pipe(gulp.dest('./dist/css'));
});


// <!-- compress -->
gulp.task('compress-main', function(){
	return gulp.src('./dist/js/webim.js')
		.pipe(rename('webim.js'))
		.pipe(uglify())
		.pipe(gulp.dest('./dist/js'));
});

gulp.task('compress-loader', function(){
	return gulp.src('./dist/js/loader.js')
		.pipe(rename('loader.js'))
		.pipe(uglify())
		.pipe(gulp.dest('./dist/js'));
});

gulp.task('compress', ['compress-main', 'compress-loader']);


// 0: dev,  1: release
var loaderLevel = 0;

// 替换根目录
var rootPath = function(){
	var stream = through.obj(function(file, enc, cb) {
		if (file.isStream()) {
			return cb();
		}

		if (file.isBuffer()) {
			var root = '$${path.mic_touch}/webim/';
			
			switch(loaderLevel){
				case 0: {
					root = '/';
				}; break;
				case 1: {
					root = '$${path.mic_touch}/webim/';
				}; break;
				default:;
			}
			
			var reg = /\{\{\=root\}\}/g;
			reg.exec("");
			file.contents = new Buffer(file.contents.toString("utf-8").replace(reg, function(){
				return root;
			}));
		}

		this.push(file);

		cb();
	});


	return stream;
};

// 替换版本戳
var version = function(){
	var stream = through.obj(function(file, enc, cb) {
		if (file.isStream()) {
			return cb();
		}

		if (file.isBuffer()) {
			var ver = new Date().valueOf();
			
			var reg = /\{\{\=version\}\}/g;
			reg.exec("");
			file.contents = new Buffer(file.contents.toString("utf-8").replace(reg, function(){
				return ver;
			}));
		}

		this.push(file);

		cb();
	});


	return stream;
};
		
// <!-- js build -->
gulp.task('js-main', function(){
	browserify({entries: './src/webim.js', debug: true})
		.transform('brfs')
		.bundle()
		.pipe(source('webim.js'))
		.pipe(buffer())
		.pipe(rootPath())
		.pipe(version())
		.pipe(sourcemaps.init({loadMaps: true}))
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('./dist/js'));
});


gulp.task('js-loader', function(){
	return gulp.src('./src/loader.js')
		.pipe(rootPath())
		.pipe(version())
		.pipe(rename('loader.js'))
		.pipe(sourcemaps.init({loadMaps: true}))
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('./dist/js'));
});

gulp.task('js', ['tpl', 'js-main', 'js-loader']);


// <!-- tpl build -->
gulp.task('tpl', function(){
	tpl({dir: 'src/tpl', root: 'tpl', dest: 'src/tpl/index.js'});
});


// <!-- start server, watch & reload server -->
gulp.task('reload', function(){
	Browsersync.reload();
});

gulp.task('watch', function(){
	//gulp.watch(['src/assets/xscript/**/*.*'], ['copy', 'reload']);
	gulp.watch(['src/**/*.js', 'src/webim.config'], ['js', 'reload']);
	gulp.watch(['src/**/*.scss'], ['scss', 'reload']);
	gulp.watch(['demo/**/*.html'], ['reload']);
	gulp.watch(['src/tpl/**/**'], ['tpl']);
});

gulp.task('watch-release', function(){
	gulp.watch(['src/**/*.js', 'src/webim.config', 'src/**/*.scss', 'demo/**/*.html', 'src/tpl/**/**'], ['release']);
});

gulp.task('build', ['copy', 'scss', 'js']);

gulp.task('server', function(){
	Browsersync.init({
		server: {
			baseDir: './',
			index: 'index.html',
			routes: {
				'/': 'demo'
			}
		},
		port: config.webim.port,
		host: config.webim.host,
		ui: config.sync.ui,
		reloadDelay: config.sync.reloadDelay,
		injectChanges: false,
		files: false,
		open: config.webim.open,
		browser: config.webim.browser
	});
	
	setTimeout(function(){
		gulp.run('watch');
	}, config.sync.reloadDelay);
});


// <!-- dev, debug, release command -->
gulp.task('devServer', ['wptr', 'build', 'server']);
gulp.task('dist', ['wptr', 'build']);


var releaseCss = function(isMstatic){
	var path = './src/css/_dev.scss';
	fs.writeFileSync(path, '$mstatic:	"' + (isMstatic ? '$${path.mic_touch}/webim' : '') + '";', {encoding: 'utf-8'});
};

gulp.task('dev', function(){
	releaseCss(false);
	loaderLevel = 0;
	
	gulp.run('devServer');
});

gulp.task('release', function(){
	releaseCss(true);
	loaderLevel = 1;
	
	gulp.run('dist');
});


gulp.task('default', ['dev']);